package com.winai.launcher.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.constant.Constant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.os.Build.UNKNOWN;

/**
 * author：康少
 * date：2019/5/17
 * description：
 */
public class BaseUtils {

    /**
     * @date 2021/2/5
     * @desc 判断某Activity是否可见
     */
    public static boolean isAPPBroughtToBackground(final Context context, String targetAppPackageName, String targetAppActivityName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> mTasks = am.getRunningTasks(1);

        if (!mTasks.isEmpty() && mTasks.get(0) != null) {
            ComponentName topActivity = mTasks.get(0).topActivity;
            if (topActivity != null && !TextUtils.isEmpty(topActivity.getPackageName()) &&
                    !TextUtils.isEmpty(topActivity.getClassName())) {
                LogUtils.d("topActivity.getPackageName() -> " + topActivity.getPackageName());
                LogUtils.d( "topActivity.getClassName() -> " + topActivity.getClassName());
                if (topActivity.getPackageName().equals(targetAppPackageName) &&
                        topActivity.getClassName().equals(targetAppActivityName)) {
                    LogUtils.d( "target Activity is in top !");
                    return true;
                } else {
                    LogUtils.d( "target Activity is not in top.");
                    return false;
                }
            } else {
                LogUtils.d( "topActivity is null or PackageName is null or ClassName is null.");
                return false;
            }
        } else {
            LogUtils.d( "mTasks.isEmpty() || mTasks.get(0) == null ");
            return false;
        }
    }

    /**
     * 截断输出超长日志
     *
     * @param msg
     */
    public static void longLog(String tag, String msg) {
        if (tag == null || tag.length() == 0
                || msg == null || msg.length() == 0)
            return;

        int segmentSize = 3 * 1024;
        long length = msg.length();
        if (length <= segmentSize) {// 长度小于等于限制直接打印
            Log.e(tag, msg);
        } else {
            while (msg.length() > segmentSize) {// 循环分段打印日志
                String logContent = msg.substring(0, segmentSize);
                msg = msg.replace(logContent, "");
                Log.e(tag, "-------------------" + logContent);
            }
            Log.e(tag, "-------------------" + msg);// 打印剩余日志
        }
    }

    /**
     * 通过key解析url中存在的value
     *
     * @param url
     * @param key
     * @return
     */
    public static String getDataFromUrl(String url, String key) {
        String value = "";
        Uri uri = Uri.parse(url);
        value = uri.getQueryParameter(key);
        return TextUtils.isEmpty(value) ? "" : value;
    }

    /**
     * 说明：获取网络时间
     */
    public static Date getNetTime() {
        String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
        String bjTime = "http://www.bjtime.cn";//北京时间
        try {
            URL url = new URL(bjTime);
            URLConnection uc = url.openConnection();
            uc.setReadTimeout(5000);
            uc.setConnectTimeout(5000);
            uc.connect();
            long correctTime = uc.getDate();
            Date date = new Date(correctTime);
            return date;
        } catch (Exception e) {
            return new Date();
        }
    }

    /**
     * @date 6/3/21
     * @desc 确保获取初始化后的时间戳，精确到秒
     */
    public static String getInitTime() {
        String currentTime = BaseUtils.getCurrentTime();
        String yymmd = BaseUtils.timeStamp2Date(currentTime, "yyyy-MM-dd");
        if (yymmd.equals("2010-01-01") || yymmd.equals("1970-01-01")) {
            Constant.isTimeInited = false;
        }
        while (!Constant.isTimeInited) {
            currentTime = BaseUtils.getCurrentTime();
            String _hhmm = BaseUtils.timeStamp2Date(currentTime, "HH:mm");
            String _yymmd = BaseUtils.timeStamp2Date(currentTime, "yyyy-MM-dd");
            if (_yymmd.equals("2010-01-01") || _yymmd.equals("1970-01-01")) {
                LogUtils.e("时间初始化中……");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                LogUtils.e("时间初始化完成：" + _yymmd + " " + _hhmm);
                Constant.isTimeInited = true;
            }
        }
        return currentTime;
    }

    /**
     * 说明：设置字体颜色渐变
     */
    public static void setTextGradient(TextView text) {
        LinearGradient mLinearGradient = new LinearGradient(
                0
                , 0
                , text.getPaint().getTextSize() * text.getText().length()
                , 0
                , Color.parseColor("#669262")
                , Color.parseColor("#7eb779")
                , Shader.TileMode.CLAMP);
        text.getPaint().setShader(mLinearGradient);
        text.invalidate();
    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * Desc 获取当前时间戳，精确到秒
     */
    public static String getCurrentTime() {
        long l = System.currentTimeMillis() / 1000;
        return String.valueOf(l);
    }

    /**
     * Desc 日期转时间戳——秒级
     */
    public static String dateToTimestamp(Date date) {
        return String.valueOf(date.getTime() / 1000);
    }

    /**
     * Desc 时间戳转日期
     */
    public static Date timestampToDate(String timestamp) {
        return new Date(Long.valueOf(timestamp) * 1000);
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到秒的字符串
     * @param format  "yyyy-MM-dd HH:mm:ss"
     * @return
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (TextUtils.isEmpty(seconds) || seconds.equals("null")) {
            return "";
        }
        if (TextUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds) * 1000));
    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param date_str 字符串日期
     * @param format   如：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String date2TimeStamp(String date_str, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        try {
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(date_str).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 说明：获取今天是星期几
     */
    public static String getCurrentDay() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(mWay)) {
            mWay = "天";
        } else if ("2".equals(mWay)) {
            mWay = "一";
        } else if ("3".equals(mWay)) {
            mWay = "二";
        } else if ("4".equals(mWay)) {
            mWay = "三";
        } else if ("5".equals(mWay)) {
            mWay = "四";
        } else if ("6".equals(mWay)) {
            mWay = "五";
        } else if ("7".equals(mWay)) {
            mWay = "六";
        }
        return "星期" + mWay;
    }

    /**
     * 根据日期来获取当前是星期几
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        // 获得一个日历
        Calendar cal = Calendar.getInstance();
        Date date = null;
        try {
            date = format.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week < 0) {
            week = 0;
        }
        return weekDays[week];
    }

    /**
     * Description：电话联系
     */
    public static void callPhone(Context mContext, String phoneNum) {
        //调用系统的拨号服务实现电话拨打功能
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    private static String getLevelStr(int level) {
        StringBuilder levelStr = new StringBuilder();
        for (int levelI = 0; levelI < level; levelI++) {
            levelStr.append("\t");
        }
        return levelStr.toString();
    }

    /**
     * 说明：获取设备SN码
     */
    @SuppressLint("HardwareIds")
    public static String getDeviceSN() {
        return Build.SERIAL;
    }

    /**
     * 说明：获取手机的唯一标识符: deviceId
     */
    @SuppressLint("HardwareIds")
    public static String getDeviceId() {
        String imei = getMac();
        String serial = Build.SERIAL;
        String uuid;
        if (TextUtils.isEmpty(imei)) {
            imei = "unkown";
        } else if (TextUtils.isEmpty(serial)) {
            serial = "unkown";
        }
        uuid = UUID.nameUUIDFromBytes((imei + serial).getBytes()).toString();
        return uuid;
    }

    /**
     * 说明：获取设备名称
     */
    @SuppressLint("HardwareIds")
    public static String getDeviceName() {
        return android.os.Build.DEVICE;
    }

    /**
     * 说明：获取设备型号
     */
    public static String getDeviceType() {
        return android.os.Build.MODEL;
    }

    /**
     * 返回当前固件版本号
     */
    public static String getDeviceVersion() {
        String value = UNKNOWN;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) (get.invoke(c, "ro.custom.build.version", UNKNOWN));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return value;
        }
    }

    /**
     * 返回当前设备版本号
     */
    public static String getSystemVersion() {
        String value = UNKNOWN;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) (get.invoke(c, "ro.custom.sys.version", UNKNOWN));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return value;
        }
    }

    /**
     * 通过网络接口取Mac
     */
    public static String getMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null || macBytes.length == 0) {
                    return null;
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 返回当前Launcher版本号（版本名）
     */
    public static String getLauncherVersion(Context context) {
        String versionName = null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public static int getLauncherVersionCode(Context mContext) {
        // 获取packagemanager的实例
        PackageManager packageManager = mContext.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        int version = 0;
        try {
            PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
            version = packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 获取ip地址
     */
    public static String getIp(WifiManager wifiManager) {
        if (wifiManager == null) {
            return "";
        }
        InetAddress inetAddress = NetworkUtils.intToInetAddress(wifiManager.getConnectionInfo().getIpAddress());
        if (inetAddress == null) {
            return "";
        }
        return inetAddress.getHostAddress();
    }

    /**
     * 获取本机的外网ip地址
     */
    public static void getV4IP(Handler mHandler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String ip = "";
                StringBuilder inputLine = new StringBuilder();
                String chinaz = "http://ip.chinaz.com";

                String read = "";
                URL url = null;
                HttpURLConnection urlConnection = null;
                BufferedReader in = null;
                try {
                    url = new URL(chinaz);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
                    while ((read = in.readLine()) != null) {
                        inputLine.append(read + "\r\n");
                    }
                    //System.out.println(inputLine.toString());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
                Matcher m = p.matcher(inputLine.toString());
                if (m.find()) {
                    String ipstr = m.group(1);
                    ip = ipstr;
                    //System.out.println(ipstr);
                }
                Message message = new Message();
                message.what = 2020;
                message.obj = ip;
                mHandler.sendMessage(message);
            }
        }).start();
    }
}
